package com.wangzhenyu.common.net

import android.app.Activity
import android.text.TextUtils
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.wangzhenyu.common.base.BaseApplication
import com.wangzhenyu.common.base.IConstant
import com.wangzhenyu.common.base.bean.UserManager
import okhttp3.Interceptor
import okhttp3.Response
import okio.Buffer
import java.io.EOFException
import java.nio.charset.Charset
import java.util.Locale
import java.util.UUID


object Fetch {

    private val UTF8 = Charset.forName("UTF-8")

    fun <T> createService(clazz: Class<T>): T {
        return RetrofitUtil.getInstance("").getRetrofit().create(clazz)
    }

    fun <T> createOtherService(clazz: Class<T>): T {
        return RetrofitUtil.getInstance("").getOtherRetrofit().create(clazz)
    }


    fun initNetConfig() {
        //把Gitee的Api给他
        RetrofitUtil.baseUrl = IConstant.getSellerUrl()
        RetrofitUtil.baseOtherUrl = IConstant.getCommonUrl()
        //在这里设置自定义Interceptor
        RetrofitUtil.interceptor = Interceptor { chain ->
            val loginInfo = UserManager.getLoginInfo()

            //获取原始的originalRequest
            val request = chain.request()
            // 获取originalRequest的创建者builder
            val newBuilder = request.newBuilder()


            //添加Header
            newBuilder.addHeader("version", "1.0")//版本名建议用BuildConfig.VERSION_NAME
            newBuilder.addHeader("uuid", DeviceUtils.getAndroidID())
            if (UserManager.isLogin() && loginInfo != null) {
                //登陆了之后要在Header上加入Authorization
                newBuilder.addHeader(
                    "Authorization",
                    loginInfo.accessToken ?: "zhe shi access token"
                )
                if (IConstant.official) {
                    //正式版做如下处理
                    val uid = loginInfo.uid?.toString()
                    //通用唯一识别码
                    val nonce = UUID.randomUUID().toString().replace("-", "").substring(0, 6)
                    val timestamp = (System.currentTimeMillis() / 1000).toString()
                    val sign =
                        EncryptUtils.encryptMD5ToString(uid + nonce + timestamp + loginInfo.accessToken)
                            .lowercase(Locale.ROOT)
                    //获取老的Url，再重新创建新的HttpUrl
                    val httpUrl = request.url.newBuilder()
                        .addQueryParameter("uid", uid ?: "uid test")
                        .addQueryParameter("nonce", nonce)
                        .addQueryParameter("timestamp", timestamp)
                        .addQueryParameter("sign", sign)
                        .build()
                    newBuilder.url(httpUrl)
                }

            }

            //获取处理后的newRequest
            val newRequest = newBuilder.build()

            val response: Response = try {
                //对新的Request对象进行网络请求
                chain.proceed(newRequest)
            } catch (e: Exception) {
                throw e
            }


            //设置Token的超时处理
            val responseBody = response.body
            val contentLength = responseBody!!.contentLength()

            //解决response.body().string();只能打印一次
            val source = responseBody.source()
            //Buffer the entire body.
            source.request(Long.MAX_VALUE)
            val buffer = source.buffer
            var charset = UTF8
            val contentType = responseBody.contentType()
            if (contentType != null) {
                charset = contentType.charset(UTF8)
            }

            if (!isPlaintext(buffer)) {
                return@Interceptor response
            }

            if (contentLength != 0L && response.code != 200) {
                val result = buffer.clone().readString(charset)
                try {
                    val gson = Gson()
                    val baseResponse = gson.fromJson(result, BaseResponse::class.java)
                    if (baseResponse != null) {
                        if (!TextUtils.isEmpty(baseResponse.message)) {
                            ToastUtils.showShort(baseResponse.message)
                        }
                        if ("403" == baseResponse.code) {
                            val loginInfo = UserManager.getLoginInfo()
                            if (loginInfo?.refreshToken == null) {
                                UserManager.loginOut()
                                goToLoginActivity()
                            } else {
//                                val response =
//                                    LoginRepository.apiService.refreshToken(loginInfo.refreshToken!!)
//                                        .execute()
//                                if (response.isSuccessful) {
//                                    loginInfo.accessToken = response.body()?.accessToken
//                                    loginInfo.refreshToken = response.body()?.refreshToken
//                                    UserManager.setLoginInfo(loginInfo)
//                                    LogUtils.d("refresh token success")
//                                } else {
//                                    goToLoginActivity()
//                                }
                            }

                        }
                    }
                } catch (e: RuntimeException) {
                    e.printStackTrace();
                }
            }


            return@Interceptor response
        }


    }

    //跳转到登陆页面
    private fun goToLoginActivity() {
        if (AppUtils.isAppForeground()) {
            BaseApplication.myApplication.loginOutByToken()
            ActivityUtils.finishAllActivities()
            ActivityUtils.startActivity(Class.forName("com.wzy.business.store.login.LoginActivity") as Class<Activity>)
        }
    }


    private fun isPlaintext(buffer: Buffer): Boolean {
        return try {
            val prefix = Buffer()
            val byteCount = if (buffer.size < 64) buffer.size else 64
            buffer.copyTo(prefix, 0, byteCount)
            for (i in 0..15) {
                if (prefix.exhausted()) {
                    break
                }
                val codePoint = prefix.readUtf8CodePoint()
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(
                        codePoint
                    )
                ) {
                    return false
                }
            }
            true
        } catch (e: EOFException) {
            false // Truncated UTF-8 sequence.
        }
    }

}